class Post {

    static hasMany = [comments: Comment, tags: Tag]

    String title
    String teaser
    String content
    Date lastUpdated
    Boolean published = false
    SortedSet comments
    SortedSet tags

    String urlTitle

    static constraints = {
        title(nullable: false, blank: false, size: 1..50)
        teaser(nullable: true, size: 0..255)
        content(nullable: false, blank: false)
        lastUpdated(nullable: true)
        published(nullable: false)
        urlTitle(nullable: true)
    }

    def beforeInsert = {
        urlTitle = title.replaceAll(" ", "_")
    }

    def beforeUpdate = {
        urlTitle = title.replaceAll(" ", "_")        
    }

    def addTag(tagName) {
        def tag = Tag.findByName(tagName)
        if (!tag) {
            tag = new Tag(name: tagName)
        }
        addToTags(tag)
    }

    def getTagsAsString() {
        return tags?.sort {it.name}?.join(" ")
    }

    def hasTag(tagName) {
        def found = false
        tags.each {
            if (it.name == tagName) {
                found = true
            }
        }
        return found
    }

    def getUnderscoredTitle() {
        return title.replaceAll(" ", "_")
    }
}
